import React, { useState, useEffect, useMemo } from 'react';
import { Modal, Button, Skeleton, Image, message, Typography, Divider, Descriptions } from 'antd'
import { UploadOutlined, LoadingOutlined, CloseOutlined } from '@ant-design/icons';

import type { UploadChangeParam } from 'antd/es/upload';
import type { RcFile, UploadFile, UploadProps } from 'antd/es/upload/interface';
import { information } from '@/utils/rules';
import Utils from 'fr-util/utils';

import {
  ProFormText,
  ProForm,
  ProFormTextArea,
  ProFormSelect,
  ProFormDependency,
  ProCard,
  CheckCard,
  DrawerForm,
} from '@ant-design/pro-components';

import EditModal from './EditModal'


import {
  reqPulseCalibrationList,
  reqTongueCalibrationList,
  reqDiagnosisTermList,
  reqDiagnosisTermListByGrade,
  reqSeniorInquiryList,
  reqSeniorInquiryUpdate,
  reqSymptomList,
  reqSymptomListByGrade,
  reqWesternMedicineList,
  reqBaseFormulaList,
  reqBaseFormulaDetailList,
  reqEtiologyCategoryList,
  reqEtiologyList,
  reqEtiologyCategoryListByDiagnosis,
  reqSeniorInquiryPrescriptionMedication,
  reqBaseFormulaDetailGetBaseFormulaHerb,
} from '@/services/firstConsultation';

import '../index.module.less'

const { Paragraph } = Typography;

interface AddModalProps {
  isShow: boolean,
  onCancel: (params: boolean) => void,
  user: any,
  upDataInfo: any,
}

const AddModal: React.FC<AddModalProps> = ({
  isShow,
  onCancel,
  user,
  upDataInfo,
}) => {

  const [formObj] = ProForm.useForm()

  const [data, setData] = useState<any>(null)
  const [messageList, setMessageList] = useState<any>(null)

  const [categoryList, setCategoryList] = useState<any>(null)

  const [selectList, setSelectList] = useState<any>(null)
  const [messageKeys, setMessage] = useState<any>([])

  // 病因是否多选
  const [isMultiPatho, setIsMultiPatho] = useState(true as boolean)


  // /api/v1/etiology/listAll
  // /api/v1/etiologyCategory/listAll
  const [initialValues, setinitialValues] = useState<any>(null)

  function arrayFormatOptions(array: []) {
    if (!Array.isArray(array)) return []
    return array.map((item: any) => ({
      label: item?.name,
      title: item?.name,
      value: item?.id,
      size: 'small',
    }))
  }



  function arrayFormatOptGroup(array: []) {
    console.log('arrayFormatOptGroup', array);
    if (!Array.isArray(array)) return []
    return array.map((item: any) => ({
      label: item?.parentDiagnosisTerm?.name,
      value: item?.parentDiagnosisTerm?.id,
      options: arrayFormatOptions(item?.diagnosisTermList)
    }))
  }

  // {
  //   label: 'Manager',
  //   options: [
  //     { label: 'Jack', value: 'jack' },
  //     { label: 'Lucy', value: 'lucy' },
  //   ],
  // },

  async function init() {
    try {
      const res = await reqDiagnosisTermListByGrade({})

      const res2 = await reqEtiologyList({})

      if (res2?.resultCode == '00000000') {
        setCategoryList(res2?.data)
      }

      console.log('诊断术语列表-分级信息 :>> ', res?.data);
      if (res?.resultCode == '00000000') {
        setData(res?.data)
      } else {
        message.error(`诊断术语列表-分级信息出错！${res?.message}`)
      }
    } catch (error: any) {
      message.error('诊断术语列表-分级信息出错！', error)
      console.log('诊断术语列表-分级信息出错！ :>> ', error);
    }
  }


  useEffect(() => {
    if (user?.id) {
      init()
    }
  }, [user])




  const [seletTyDiagnosisIds, setSeletTyDiagnosisIds] = useState([] as number[])

  function onChangeCheckCard(tyDiagnosisIds: any) {
    // setSeletTyDiagnosisIds(tyDiagnosisIds)
  }


  async function getCheckCardList(tyDiagnosisIds: any) {
    const errLogName = '根据诊断术语信息查询病因'
    if (!tyDiagnosisIds?.length) return;
    // try {
    //   const res = await reqEtiologyCategoryListByDiagnosis({
    //     tyDiagnosisIds
    //   })
    //   console.log(`${errLogName}信息 :>> `, res?.data);
    //   if (res?.resultCode == '00000000') {
    //     setMessageList(res?.data)
    //   } else {
    //     message.error(`${errLogName}信息出错！${res?.message}`)
    //   }
    // } catch (error: any) {
    //   message.error(`${errLogName}信息出错！`, error)
    //   console.log(`${errLogName}信息出错！ :>> `, error);
    // }
  }


  useEffect(() => {
    if (seletTyDiagnosisIds?.length > 0) {
      getCheckCardList(seletTyDiagnosisIds)
    }

  }, [seletTyDiagnosisIds])

  // 候选区列表更改
  function onChangeCategoryList(values: any) {
    const newArr = JSON.parse(JSON.stringify(messageKeys));
    messageKeys.map((item: any, index: number) => {
      const isSome = messageList.some((li: any) => li?.id == item);
      if (isSome) {
        if (!values.includes(item)) {
          newArr.splice(index, 1)
        }
      }
    })

    console.log('候选区列表更改 :>> ', messageList, messageKeys, values, newArr);

    const array = [...newArr, ...values];
    const uniqueArray = Array.from(new Set(array));
    setMessage(uniqueArray)
  }

  // 已选择区列表更改
  function onChangeSelectList(value: any) {
    console.log('已选择区列表更改 :>> ', value);
    value && setSelectList(value)
  }

  const [isOpen, setIsOpen] = useState<Boolean | undefined>(false)

  function handleModal(bool: Boolean, list?: any) {
    if (list) {
      console.log('handleModal', list);
      setMessage(list)
    }
    setIsOpen(bool)
  }

  const mapObj = useMemo(() => {
    let obj = {};
    categoryList?.map((item: any) => {
      item?.etiologyList?.map((li: any) => {
        obj[li.id] = li;
      })
    })
    return obj;
  }, [categoryList])

  const datamMpObj = useMemo(() => {
    let obj = {};
    data?.map((item: any) => {
      item?.diagnosisTermList?.map((li: any) => {
        obj[li.id] = {
          ...li, parentDiagnosisTerm: item?.parentDiagnosisTerm
        };
      })
    })
    return obj;
  }, [data])

  // console.log('categoryList :>> ',
  //   datamMpObj,
  //   messageKeys,
  //   selectList,
  //   categoryList,
  //   mapObj,
  //   data,
  //   seletTyDiagnosisIds
  // );

  const textMessage = mapObj &&
    (selectList == 0 || selectList) && mapObj[selectList];

  const tyDiagnosisInfo = useMemo(() => {
    return user?.seniorInquiry?.tyDiagnosisTermJson && JSON.parse(user?.seniorInquiry?.tyDiagnosisTermJson);
  }, [user])
  const [isEdit, setIsEdit] = useState(tyDiagnosisInfo)


  async function onFinish(values: any) {

    // console.log('输入病史 :>> ', values, messageKeys, seletTyDiagnosisIds);
    let mapArr = {};
    seletTyDiagnosisIds?.map((item: any) => {
      const key = datamMpObj[item]?.parentDiagnosisTerm?.id
      if (key && mapArr[key] && mapArr[key].child) {
        mapArr[key].child.push({
          name: datamMpObj[item]?.name,
          id: datamMpObj[item]?.id,
        });
      } else {
        mapArr[key] = {
          child: [{
            id: datamMpObj[item]?.id,
            name: datamMpObj[item]?.name,
          }],
          ...datamMpObj[item].parentDiagnosisTerm
        };
      }
      return null;
    })

    console.log('mapArr :>> ', mapArr);
    const tyDiagnosisJson = Object.values(mapArr);
    const messageJson = messageKeys?.map((item: any) => {
      return {
        id: mapObj[item].id,
        name: mapObj[item].name
      };
    })



    const tyDiagnosisTermJson = { tyDiagnosisJson, messageJson };
    console.log('messageJson', values, messageJson, user?.seniorInquiry);


    // console.log('tyDiagnosisTermJson =========:>> ', tyDiagnosisTermJson);
    try {
      upDataInfo && await upDataInfo({
        ...user?.seniorInquiry,
        ...values,
        tyDiagnosisTermJson: JSON.stringify(tyDiagnosisTermJson),
      })

      onCancel(false)
    } catch (error) {
      message.info(error?.meessage)
    }

    !isEdit && setIsEdit(true)
  }

  const filterAndExtractIds = (data: any[], terms: string[]) => {
    const includedJinIds: number[] = [];
    const includedYeIds: number[] = [];
    const excludedIds: number[] = [];

    const termSet = new Set(terms);

    data.forEach((parent) => {
      const { parentDiagnosisTerm, diagnosisTermList } = parent;
      const parentName = parentDiagnosisTerm.name;
      if (termSet.has(parentName)) {
        const targetArray = parentName === '津' ? includedJinIds : includedYeIds;
        diagnosisTermList.forEach((item: { id: number }) => targetArray.push(item.id));
      } else {
        diagnosisTermList.forEach((item: { id: number }) => excludedIds.push(item.id));
      }
    });

    return { includedJinIds, includedYeIds, excludedIds };
  };


  const updaterCheckout = (array: number[], id: number, includedYeIds: number[], includedJinIds: number[]): number[] => {
    let newArray = [...array];
    if (includedJinIds.includes(id)) {
      // 移除任何现有的 includedJinIds 元素
      newArray = newArray.filter(item => !includedJinIds.includes(item));
    } else if (includedYeIds.includes(id)) {
      // 移除任何现有的 includedYeIds 元素
      newArray = newArray.filter(item => !includedYeIds.includes(item));
    }
    // 如果 id 不在数组中，则将其添加到数组中
    if (!newArray.includes(id)) {
      newArray.push(id);
    }
    return newArray;
  }

  const handleCangeMultiPatho = (value: boolean, params: any) => {
    const { includedJinIds, includedYeIds } = filterAndExtractIds(data, ['津', '液']);
    if (value) {
      const updatedArray = updaterCheckout(seletTyDiagnosisIds, params.value, includedYeIds, includedJinIds,)
      console.log('updatedArray', updatedArray);
      setSeletTyDiagnosisIds(updatedArray)
    } else {
      const removeArray = seletTyDiagnosisIds.filter((item) => item !== params.value);
      setSeletTyDiagnosisIds(removeArray);
    }
  }

  // function onClose() {
  //   setIsEdit(true)
  // }

  useEffect(() => {
    if (tyDiagnosisInfo?.tyDiagnosisJson) {
      let arr: any = [];
      tyDiagnosisInfo?.tyDiagnosisJson?.map((item: any, index: number) => {
        item?.child?.map((li: any, i: number) => {
          arr.push(li?.id)
        })
      })
      console.log('tyDiagnosisInfo arr==== :>> ', arr);
      setSeletTyDiagnosisIds(arr)
    }
  }, [tyDiagnosisInfo?.tyDiagnosisJson])

  useEffect(() => {
    if (messageKeys?.length > 0) {
      setSelectList(messageKeys[messageKeys.length - 1])
    }
  }, [messageKeys])


  useEffect(() => {
    if (tyDiagnosisInfo?.messageJson) {
      let arr: any = [];
      tyDiagnosisInfo?.messageJson?.map((item: any) => {
        arr.push(item?.id)
      })
      setMessage(arr)
    }
  }, [tyDiagnosisInfo?.messageJson])

  useEffect(() => {
    if (user?.seniorInquiry?.doctorAdvice && isEdit && tyDiagnosisInfo) {
      formObj.setFieldValue('doctorAdvice', user?.seniorInquiry?.doctorAdvice);
    }
  }, [isEdit, user, tyDiagnosisInfo])


  return (
    <DrawerForm
      width={'90vw'}
      form={formObj}
      title="诊断编辑"
      visible={isShow}
      onVisibleChange={(val: boolean) => onCancel(val)}
      onFinish={(values): Promise<any> => onFinish(values)}
      modalProps={{
        destroyOnClose: true,
        onCancel: () => console.log('Cancelled'),
      }}
    >
      <ProCard split="vertical">
        {/* ledt */}
        <ProCard title={<div className='diagnosis-suggest'>诊断</div>} colSpan="65%" className='pathogen-modal-card'>
          <div className='checkCardWrap'>
            <CheckCard.Group
              multiple={isMultiPatho}
              value={seletTyDiagnosisIds}
              onChange={onChangeCheckCard}
            >
              {
                arrayFormatOptGroup(data)?.map((item, index) => {
                  return (
                    <div key={index} className='pathogen-modal-group'>
                      {/* <h3 style={{ textAlign: 'center' }}>{item?.label}</h3> */}
                      <Typography.Title type="danger" strong level={5} style={{ margin: '0 0 10px 0' }}>
                        {item?.label}
                      </Typography.Title>
                      {
                        item?.options?.map((li, i) => (
                          <CheckCard
                            className='checkCard'
                            key={i}
                            title={li?.title}
                            value={li?.value}
                            onChange={(value) => handleCangeMultiPatho(value, li)}
                          />

                        ))
                      }

                    </div>
                  )
                })
              }
            </CheckCard.Group>
            <div style={{ marginTop: '40px' }}> <ProFormTextArea width={800} name="doctorAdvice" label={<div className='diagnosis-suggest'>
              医生建议
            </div>} placeholder="请输入您的建议..." /></div>
          </div>
        </ProCard>

        {/* right */}
        <ProCard className='rightNoPadding'>
          <div>
            <div>
              {
                isOpen &&
                <EditModal
                  isOpen={isOpen}
                  categoryList={categoryList}
                  handleModal={handleModal}
                  defArr={messageKeys}
                />
              }
              <div className='selectBox'>
                <Descriptions title='已选择' bordered layout="horizontal" />
                <Button type='link' onClick={() => handleModal(true)}>选择病因</Button>
              </div>
              <CheckCard.Group
                value={selectList}
                onChange={onChangeSelectList}
              >
                {
                  messageKeys?.map((id: any, i: number) => (
                    <CheckCard
                      className='check-card-right'
                      // style={{ width: '132px' }}
                      key={id}
                      title={mapObj && mapObj[id] && mapObj[id]?.name}
                      value={id}
                    />
                  ))
                }
              </CheckCard.Group>
            </div>
            <div>
              <Descriptions title='候选区' bordered layout="horizontal" />
              <CheckCard.Group
                value={messageKeys}
                multiple
                onChange={onChangeCategoryList}
              >
                {
                  messageList?.map((li: any, i: number) => (
                    <CheckCard
                      className='checkCard'
                      key={i}
                      title={li?.name}
                      value={li?.id}
                    />
                  ))
                }
              </CheckCard.Group>
            </div>
          </div>
          {
            textMessage &&
            (
              <Descriptions column={20} title='描述区' bordered layout="horizontal">
                <Descriptions.Item span={24} label="同义词">{textMessage?.name}</Descriptions.Item>
                <Descriptions.Item span={24} label="概要">{textMessage?.summary}</Descriptions.Item>
                <Descriptions.Item span={24} label="常见症状">{textMessage?.commonSymptom}</Descriptions.Item>
                <Descriptions.Item span={24} label="治法治则">{textMessage?.ruleLaw}</Descriptions.Item>
                <Descriptions.Item span={24} label="代表方药">{textMessage?.representingMedicine}</Descriptions.Item>
                {/* 
                <h3></h3>
                <div></div>
                <h3>概要：</h3>
                <div>{textMessage?.summary}</div>
                <h3>常见症状：</h3>
                <div>{textMessage?.commonSymptom}</div>
                <h3>治法治则：</h3>
                <div>{textMessage?.ruleLaw}</div>
                <h3>代表方药：</h3>
                <div>{textMessage?.representingMedicine}</div> */}
              </Descriptions>
            )
          }
        </ProCard>
      </ProCard>
    </DrawerForm >
  );
};
export default AddModal;

